import 'reflect-metadata'
import * as Typeorm from 'typeorm'
import { Entity as RouterEntity, Column as RouterColumn, PrimaryGeneratedColumn as RouterPrimaryGeneratedColumn } from 'typeorm'
import Redis, { Entity as RedisEntity, Column as RedisColumn } from '../redis'

export * from 'typeorm'

type EntityDecorator = typeof RouterEntity

export const Entity: EntityDecorator = (...args) => {
  return function(constructor: Function) {
    RouterEntity.apply(Typeorm, args)(constructor)
    RedisEntity.apply(Redis, args)(constructor)
  }
}

type ColumnDecorator = typeof RouterColumn

export const Column: ColumnDecorator = (...args) => {
  return function(target: any, propertyKey: string) {
    RouterColumn.apply(Typeorm, args)(target, propertyKey)
    RedisColumn.apply(Redis, args)(target, propertyKey)
  }
}

type PrimaryGeneratedColumnDecorator = typeof RouterColumn

export const PrimaryGeneratedColumn: PrimaryGeneratedColumnDecorator = (...args) => {
  return function(target: any, propertyKey: string) {
    RouterPrimaryGeneratedColumn.apply(Typeorm, args)(target, propertyKey)
    RedisColumn.apply(Redis, args)(target, propertyKey)
  }
}

export const createConnection = (entities?: (string | Function | Typeorm.EntitySchema<any>)[]) => {
  return Typeorm.createConnection({
    type: 'mysql',
    host: process.env.MYSQL_HOST,
    port: process.env.MYSQL_PORT ? Number(process.env.MYSQL_PORT) : undefined,
    username: process.env.MYSQL_USERNAME,
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DATABASE,
    synchronize: false,
    logging: true,
    charset: 'utf8mb4',
    dateStrings: true,
    timezone: "+08:00",
    entities: entities
  })
}